package com.sf.marathon.soul.core.util;


import java.io.PrintWriter;
import java.io.StringWriter;

import com.sf.marathon.soul.core.base.BusinessException;
import com.sf.marathon.soul.core.base.JsonResult;

public class CommonUtils {

    private CommonUtils() {
    }

    /**
     * 获取异常信息，如果是自定义异常，则返回自定义信息；其他则返回异常堆栈
     *
     * @param e
     * @return
     */
    public static String getExceptionMsg(Exception e) {
        if (e instanceof BusinessException) {
            return e.getMessage();
        } else {
            return getStackTrace(e);
        }
    }

    /**
     * 获取异常的堆栈信息
     *
     * @param t
     * @return
     */
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            t.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }


    public static <T> JsonResult<T> getDefaultJsonResult(T data) {
        JsonResult<T> result = new JsonResult();
        result.setData(data);
        return result;
    }

}
